try:
    import Image
except ImportError:
    from PIL import Image

from django import forms
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin

from models import Album, Imagem

    



class AdminAlbum(ModelAdmin):
    list_display = ('titulo',)
    search_fields = ('titulo',)

    def save_model(self, request, obj, form, change):
            super(AdminAlbum, self).save_model(request, obj, form, change)

            extensao = obj.imagem_capa.name.split('.')[-1]
            obj.thumbnail = 'fotos/galeria/capa/%s.%s'%(obj.id, extensao)
            capa = Image.open(obj.imagem_capa.path)
            capa.thumbnail((150,150), Image.ANTIALIAS)
            capa.save(obj.imagem_capa.path)

            obj.save()


class FormImagem(forms.ModelForm):
    class Meta:
        models = Imagem
        
 
class AdminImagem(ModelAdmin):
    list_display = ('album', 'titulo',)
    search_fields = ('titulo', 'descricao',)
    list_filter = ('album',)
    form = FormImagem
    
    def save_model(self, request, obj, form, change):
        """Metodo declarado para criar miniatura da imagem depois de salvar"""
        super(AdminImagem, self).save_model(request, obj, form, change)

        if 'original' in form.changed_data:
            extensao = obj.original.name.split('.')[-1]
            obj.thumbnail = 'fotos/galeria/thumbnail/%s.%s'%(obj.id, extensao)

            miniatura = Image.open(obj.original.path)
            original = Image.open(obj.original.path)
            original.thumbnail((500,500), Image.ANTIALIAS)
            miniatura.thumbnail((100,100), Image.ANTIALIAS)
            miniatura.save(obj.thumbnail.path)
            original.save(obj.original.path)


            obj.save()
        
    
admin.site.register(Album, AdminAlbum) 
admin.site.register(Imagem, AdminImagem)